import $ from "jquery";
// cookie相关操作
function cookieCtrl() {
    this.getItem = function(key) {
        return this.getCookie(key);
    };

    this.setItem = function(key, value, hour) {
        this.addCookie(key, value, hour);
    };

    this.removeItem = function(key) {
        this.removeCookie(key);
    };
}

cookieCtrl.prototype.getCookie = function(objName) {
    var arrStr = document.cookie.split("; ");
    for (var i = 0; i < arrStr.length; i++) {
        var temp = arrStr[i].split("=");
        if (temp[0] == objName) return unescape(temp[1]);
    }
}
cookieCtrl.prototype.addCookie = function(objName, objValue, objHours) {
    var str = objName + "=" + escape(objValue);
    if (objHours > 0) { //为时不设定过期时间，浏览器关闭时cookie自动消失
        var date = new Date();
        var ms = objHours * 3600 * 1000;
        date.setTime(date.getTime() + ms);
        str += "; expires=" + date.toGMTString();
    }
    document.cookie = str;
}
cookieCtrl.prototype.removeCookie = function(objName) {
    var date = new Date();
    date.setTime(date.getTime() - 10000);
    document.cookie = name + "=a; expires=" + date.toGMTString();
}
var cookies = new cookieCtrl();

// 初始变量
var commPools = {
        isMiniProgram: window.__wxjs_environment === 'miniprogram',
        picWidth: 30, //图标宽度
        picRealWidth: 60, //图标实际宽度
        picHeight: 30, //图标高度
        picRealHeight: 60, //图标实际高度
        rotatePic: "@/assets/images/icon_rotate@3x.png", //旋转图标
        removePic: "@/assets/images/icon_close@3x.png", //移除图标ƒ
        scalePic: "@/assets/images/scale.png", //放大图标
        mouseStatus: false,
    }
    // 获取设备宽高
var _w_width = $(window).width(),
    _w_height = $(window).height();

// 方法库
var _comm = {
    debug: false,
    commPools: commPools,
    cookie: cookies,
    substitute: function(str, data) {
        if (data && typeof(data) == 'object') {
            return str.replace(/\{([^{}]+)\}/g, function(match, key) {
                var value = data[key];
                return (value !== undefined) ? '' + value : '';
            });
        } else {
            return str.toString();
        }
    },
    createCanvas: function() {
        var canvas = document.createElement("canvas");
        if (!window.devicePixelRatio)
            window.devicePixelRatio = 1;
        canvas.width = (document.documentElement.clientWidth || canvas.width) * window.devicePixelRatio;
        canvas.height = (document.documentElement.clientHeight || canvas.height) * window.devicePixelRatio;
        return canvas;
    },
    group: function(msg) {
        if (console) {
            if (typeof(msg) === "string") {
                msg = [msg];
            }
            _comm.debug && console.group.call(console, msg);
        }
    },
    randomStr: function(len) {　　
        len = len || 32;　　
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';　　
        var maxPos = chars.length;　　
        var pwd = '';　　
        for (var i = 0; i < len; i++) {　　
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    },
    toBlob: function(urlData, fileType) {
        var bytes = window.atob(urlData),
            n = bytes.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bytes.charCodeAt(n);
        }
        return new Blob([u8arr], { type: fileType });
    },
    uploadBase64Data: function(base64Img, callback) {
        var that = this;
        var base64 = base64Img.split(',')[1];
        var fileType = base64Img.split(';')[0].split(':')[1];
        var blob = this.toBlob(base64, fileType);

        var reader = new FileReader();
        reader.readAsArrayBuffer(blob);

        reader.onload = function(event) {
            that.bufferToIMG(0, blob, callback)
        }
    },
    bufferToIMG: function(retime, blob, callback) {
        var that = this;
        var client = new OSS.Wrapper({
            secure: true,
            region: 'oss-cn-beijing',
            accessKeyId: 'LTAILrPvcXC3s7Us',
            accessKeySecret: '3tL8dCVYOW2L5BcKr5jjkIXiATIXos',
            bucket: 'aupcdn'
        });
        var pathPrefix = ''
        var time = new Date().getTime();
        var storeAs = "pics/" + that.GenFileName() + '.' + blob.type.split('/')[1];
        var buffer = new OSS.Buffer(event.target.result);
        var retimes = 1;
        //alert('...');
        client.put(storeAs, buffer).then(function(result) {

            if (result.res.status == 200) {
                callback({
                    code: 200,
                    result: pathPrefix + result.name
                });
            } else {
                callback({
                    code: 500,
                    result: ''
                });
            }


        }).catch(function(err) {
            if (retime == 1) {
                callback({
                    code: 500,
                    result: ''
                });
            } else {
                that.bufferToIMG(1, blob, callback);
            }
        });

    },
    convertImgToBase64: function(url, callback) {
        var that = this;
        var width = 0,
            height = 0;
        if (typeof(url) == "object") {
            url = url.url;
            width = url.width;
            height = url.height;
        }
        if (!commPools[url]) {
            commPools[url] = 0;
        }
        commPools[url]++;

        if (url && url.indexOf("data:image/") < 0) {
            var canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d'),
                img = new Image;
            img.src = url;
            canvas.height = height || this.height;
            canvas.width = width || this.width;
            ctx.drawImage(img, 0, 0);
            var dataURL = canvas.toDataURL('image/png');
            callback.call(this, dataURL, img.width, img.height);
        } else { //如果图片为为base64  则直接输出
            callback.call(this, url);
        }
    },
    getBase64Data: function(imgbase64) {
        if (imgbase64) {
            imgbase64 = imgbase64.replace(/(data:image\/)(.*)(;base64,)/gi, "");
        }
        return imgbase64;
    },
    transformPoint: function(x, y, m) {
        return { x: m.a * x + m.c * y + m.e, y: m.b * x + m.d * y + m.f };
    },
    changeMatrix: function(matrix) {
        return matrix.replace(/\s/g, ",");
    },
    revertMatrix: function(matrix) {
        return matrix.replace(/,/g, " ");
    },
    transformBox: function(l, t, w, h, m) {
        var topleft = { x: l, y: t },
            topright = { x: (l + w), y: t },
            botright = { x: (l + w), y: (t + h) },
            botleft = { x: l, y: (t + h) };
        var transformPoint = common.transformPoint;
        topleft = transformPoint(topleft.x, topleft.y, m);
        var minx = topleft.x,
            maxx = topleft.x,
            miny = topleft.y,
            maxy = topleft.y;
        topright = transformPoint(topright.x, topright.y, m);
        minx = Math.min(minx, topright.x);
        maxx = Math.max(maxx, topright.x);
        miny = Math.min(miny, topright.y);
        maxy = Math.max(maxy, topright.y);
        botleft = transformPoint(botleft.x, botleft.y, m);
        minx = Math.min(minx, botleft.x);
        maxx = Math.max(maxx, botleft.x);
        miny = Math.min(miny, botleft.y);
        maxy = Math.max(maxy, botleft.y);
        botright = transformPoint(botright.x, botright.y, m);
        minx = Math.min(minx, botright.x);
        maxx = Math.max(maxx, botright.x);
        miny = Math.min(miny, botright.y);
        maxy = Math.max(maxy, botright.y);
        var center = { x: (topleft.x + botright.x) / 2, y: (topleft.y + botright.y) / 2 },
            r = Math.sqrt(Math.pow(topleft.x - botright.x, 2) + Math.pow(topleft.y - botright.y, 2)) / 2;
        return {
            tl: topleft,
            tr: topright,
            bl: botleft,
            br: botright,
            r: r,
            center: center,
            aabox: { x: minx, y: miny, width: (maxx - minx), height: (maxy - miny) }
        };
    },
    //获取鼠标坐标
    getMousePosition: function(e, offset) {
        if (!offset.ratio) {
            offset.ratio = 1;
        }
        var x = e.clientX || e.pageX;
        var y = e.clientY || e.pageY;
        return { x: (x - offset.x) / offset.ratio, y: (y - offset.y) / offset.ratio };
    },
    isDragging: function(e) {
        var changed = e.changedTouches.length,
            touching = e.touches.length;
        return changed === 1 && touching === 1;
    },
    isPinching: function(e) {
        var changed = e.changedTouches.length,
            touching = e.touches.length;
        return (changed === 1 || changed === 2) && touching === 2;
    },
    getTouchedPosition: function(e, offset) {
        if (!offset) {
            offset = { x: 0, y: 0, ratio: 1 };
        }
        if (!offset.ratio) {
            offset.ratio = 1;
        }
        var length = e.touches.length;
        switch (length) {
            case 1:
                return { point1: { x: (e.touches[0].pageX - offset.x) / offset.ratio, y: (e.touches[0].pageY - offset.y) / offset.ratio }, length: length };
            case 2:
                // m[0].set(e.touches[0].pageX, e.touches[0].pageY, 0);
                // m[1].set(e.touches[1].pageX, e.touches[1].pageY, 0);
                return {
                    point1: { x: (e.touches[0].pageX - offset.x) / offset.ratio, y: (e.touches[0].pageY - offset.y) / offset.ratio },
                    point2: { x: (e.touches[1].pageX - offset.x) / offset.ratio, y: (e.touches[1].pageY - offset.y) / offset.ratio },
                    length: length
                };
            default:
                return { point1: { x: (e.changedTouches[0].pageX - offset.x) / offset.ratio, y: (e.changedTouches[0].pageY - offset.y) / offset.ratio }, length: length };
        }
    },
    each: function(item, callback) {
        // var len=this.length;
        for (var i in item) {
            if (callback) {
                callback(item[i], i);
            }
        }
    },
    prototypeDefine: function() {
        //为svg对象设置数组原型方法
        $.extend(Array.prototype, {
            hide: function(callback) {
                var len = this.length;
                for (var i = 0; i < len; i++) {
                    if (callback) {
                        callback(this[i], i);
                    } else {
                        this[i].hide();
                    }
                }
            },
            show: function(callback) {
                var len = this.length;
                for (var i = 0; i < len; i++) {
                    if (callback) {
                        callback(this[i], i);
                    } else {
                        this[i].show();
                    }
                }
            },
            each: function(callback) {
                var len = this.length;
                for (var i = 0; i < len; i++) {
                    callback(this[i], i);
                }
            },
            remove: function(callback) {
                var len = this.length;
                for (var i = 0; i < len; i++) {
                    if (callback) {
                        callback(this[i], i);
                    } else {
                        this[i].remove();
                    }
                }
            }
        });
        $.extend(Object.prototype, {});
    },
}
export default _comm;